package yxy.game.pm2.command.pack;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.item;
import yxy.cherry.data.bean.optionaldate;
import yxy.cherry.data.bean.packagedata;
import yxy.cherry.data.bean.randomdrop;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Item;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.PackageHandle;
import yxy.game.pm2.module.conquest.ConquestHandle;
import yxy.game.pm2.module.conquest.ConquestModule;

import java.util.ArrayList;

/**
 * 背包 物品使用
 */
@MessageType(proto = Command.ItemUse, classtype = PackageMessage.ItemUseRequest.class)
public class CMD_ItemUse extends Command<PackageMessage.ItemUseRequest> {

    @Override
    public void execute(MessageSource messageSource, PackageMessage.ItemUseRequest request) {
        String playerCode = messageSource.getTag();
        int dataId = request.getDataId();
        int param = request.getParam();
        int num = request.getNum();

        PackageMessage.ItemUseResponse.Builder response = PackageMessage.ItemUseResponse.newBuilder();

        item data = DataCenter.getData(dataId, item.class);
        if (data == null || num < 1) {
            send(messageSource, response, Result.ParamError);
            return;
        }
        if (Currency.number(playerCode, CurrencyType.CT_物品, dataId,false) < num) {
            send(messageSource, response, Result.PackItemNumberLack);// 数量不够
            return;
        }

        try {
            switch (data.getType()) {
                case 1:// 固定奖励packageId
                {
                    //新增动态奖励（6，12，24小时）
                    if (isNewReward(playerCode, data, dataId, messageSource, response, num)) break;


                    packagedata _packagedata = DataCenter.getData(data.getPackageid(), packagedata.class);
                    if (_packagedata == null) {
                        send(messageSource, response, Result.DataError);
                        return;
                    }


                    Currency cost = Currency.create(CurrencyType.CT_物品, dataId, num);
                    Currencies rewards = new Currencies(Currency.create(_packagedata.getRewardtype(), _packagedata.getRewardid(), _packagedata.getRewardnum()));
                    for (Currency currency : rewards) {
                        currency.setNumber(currency.getNumber() * num);
                    }

                    Result result = new PackageHandle().exchange(playerCode, new Currencies(cost), rewards, CCReason.物品使用);
                    if (!result.equals(Result.Success)) {
                        send(messageSource, response, result);
                        break;
                    }
                    response.setItem(new CurrencyHandle().packItem(Item.get(playerCode, CurrencyType.CT_物品, dataId)));
                    response.addAllReward(new CurrencyHandle().packItems(rewards));
                    send(messageSource, response, Result.Success);
                }
                break;
                case 2:// 随机奖励randomId
                {
                    randomdrop _randomdrop = DataCenter.getData(data.getRandomid(), randomdrop.class);
                    if (_randomdrop == null) {
                        send(messageSource, response, Result.DataError);
                        return;
                    }

                    Currency cost = Currency.create(CurrencyType.CT_物品, dataId, num);
                    Currencies rewards = new Currencies();
                    for (int i = 0; i < num; i++) {
                        rewards.add(new PackageHandle().randomCurrency(_randomdrop, data.getNum()));
                    }

                    Result result = new PackageHandle().exchange(playerCode, new Currencies(cost), rewards, CCReason.物品使用);
                    if (!result.equals(Result.Success)) {
                        send(messageSource, response, result);
                        break;
                    }
                    response.setItem(new CurrencyHandle().packItem(Item.get(playerCode, CurrencyType.CT_物品, dataId)));
                    response.addAllReward(new CurrencyHandle().packItems(rewards));
                    send(messageSource, response, Result.Success);
                }
                break;
                case 3:// 自选奖励optional
                {

                    optionaldate _optionaldate = DataCenter.getData(param, optionaldate.class);
                    int groupid = data.getOptionalgid();
                    if (_optionaldate == null || _optionaldate.getOptionalgroup() != groupid) {
                        send(messageSource, response, Result.DataError);
                        return;
                    }

                    Currency cost = Currency.create(CurrencyType.CT_物品, dataId, num);
                    Currencies rewards = new Currencies(Currency.create(_optionaldate.getRewardtype(), _optionaldate.getRewardid(), _optionaldate.getRewardnum() * num));
                    Result result = new PackageHandle().exchange(playerCode, new Currencies(cost), rewards, CCReason.物品使用);
                    if (!result.equals(Result.Success)) {
                        send(messageSource, response, result);
                        break;
                    }
                    response.setItem(new CurrencyHandle().packItem(Item.get(playerCode, CurrencyType.CT_物品, dataId)));
                    response.addAllReward(new CurrencyHandle().packItems(rewards));
                    send(messageSource, response, Result.Success);
                }
                break;
            }
        } catch (Exception e) {
            send(messageSource, response, Result.DataError);
        }

    }


    //判断物品id   如果是新增的那个动态礼包  就返回该奖励
    private boolean isNewReward(String playerCode, item data, int id, MessageSource messageSource, PackageMessage.ItemUseResponse.Builder response, int num) {

        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 8001; i <= 8024; i++) {
            list.add(i);
        }

        if (list.contains(id)) {
            String gtype = data.getGtype();
            String[] str = gtype.split("_");
            //银币    str[0]:类型  str[1]:小时
            if (str[0].equals("2")) {
                getSilver(playerCode, id, messageSource, response, str[1], num);
            }
            //经验
            if (str[0].equals("3")) {
                getExperience(playerCode, id, messageSource, response, str[1], num);
            }
            //将星玉
            if (str[0].equals("5")) {
                getJade(playerCode, id, messageSource, response, str[1], num);
            }
            return true;
        }
        return false;
    }

    private void send(MessageSource messageSource, PackageMessage.ItemUseResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }


    //根据时间获取银币
    private void getSilver(String playerCode, int dataId, MessageSource messageSource, PackageMessage.ItemUseResponse.Builder response, String time, int num) {
        try {
            Currency cost = Currency.create(CurrencyType.CT_物品, dataId, num);
            long passTime = Long.parseLong(time) * 60 * 1000 * num;
            ConquestModule conquestModule = ConquestModule.get(playerCode);
            Currencies rewards = ConquestHandle.holdRewardOnlyCoin(conquestModule.getMapId(), passTime);
            Result result = new PackageHandle().exchange(playerCode, new Currencies(cost), rewards, CCReason.物品使用);
            if (!result.equals(Result.Success)) {
                send(messageSource, response, result);
            }
            response.setItem(new CurrencyHandle().packItem(Item.get(playerCode, CurrencyType.CT_物品, dataId)));
            response.addAllReward(new CurrencyHandle().packItems(rewards));
            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //根据时间获取经验
    private void getExperience(String playerCode, int dataId, MessageSource messageSource, PackageMessage.ItemUseResponse.Builder response, String time, int num) {
        try {
            Currency cost = Currency.create(CurrencyType.CT_物品, dataId, num);
            long passTime = Long.parseLong(time)  * 60 * 1000 * num;
            ConquestModule conquestModule = ConquestModule.get(playerCode);
            Currencies rewards = ConquestHandle.holdRewardOnlyHeroexp(conquestModule.getMapId(), passTime);
            Result result = new PackageHandle().exchange(playerCode, new Currencies(cost), rewards, CCReason.物品使用);
            if (!result.equals(Result.Success)) {
                send(messageSource, response, result);
            }
            response.setItem(new CurrencyHandle().packItem(Item.get(playerCode, CurrencyType.CT_物品, dataId)));
            response.addAllReward(new CurrencyHandle().packItems(rewards));
            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //根据时间获取将星玉
    private void getJade(String playerCode, int dataId, MessageSource messageSource, PackageMessage.ItemUseResponse.Builder response, String time, int num) {
        try {
            Currency cost = Currency.create(CurrencyType.CT_物品, dataId, num);
            long passTime = Long.parseLong(time)  * 60 * 1000 * num;
            ConquestModule conquestModule = ConquestModule.get(playerCode);
            Currencies rewards = ConquestHandle.sweepRewardOnlyJade(conquestModule.getMapId(), passTime);
            Result result = new PackageHandle().exchange(playerCode, new Currencies(cost), rewards, CCReason.物品使用);
            if (!result.equals(Result.Success)) {
                send(messageSource, response, result);
            }
            response.setItem(new CurrencyHandle().packItem(Item.get(playerCode, CurrencyType.CT_物品, dataId)));
            response.addAllReward(new CurrencyHandle().packItems(rewards));
            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}